package com.yixin.hospital.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yixin.hospital.common.ApiResult;
import com.yixin.hospital.entity.bo.PageInfo;
import com.yixin.hospital.entity.domain.ReturnPaid;
import com.yixin.hospital.entity.dto.req.returnpaid.ReturnPaidReqDto;
import com.yixin.hospital.entity.vo.ReturnPaidVo;
import com.yixin.hospital.enums.ReturnPaidEnum;
import com.yixin.hospital.mapper.ReturnPaidMapper;
import com.yixin.hospital.mapper.extend.ReturnPaidExtendMapper;
import com.yixin.hospital.service.ReturnPaidService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * @author Administrator
 * @description 针对表【paid(欠款表)】的数据库操作Service
 * @createDate 2025-06-30 00:18:17
 */
@Service
public class ReturnPaidServiceImpl extends ServiceImpl<ReturnPaidMapper, ReturnPaid>
    implements ReturnPaidService {

    @Resource
    private ReturnPaidExtendMapper returnPaidExtendMapper;


    @Override
    public ApiResult<PageInfo<ReturnPaidVo>> getCurVisitAmount(int currentPage, int pageSize, Long deptId, Long workAddressId, Long jobOfficeId, String guidanceCode, Integer status) {
        IPage<ReturnPaidVo> returnPaidVoIPage = returnPaidExtendMapper.pageVo(Page.of(currentPage, pageSize), guidanceCode, status, deptId);
        PageInfo<ReturnPaidVo> listGuidanceVOPageInfo = new PageInfo<>();
        BeanUtils.copyProperties(returnPaidVoIPage, listGuidanceVOPageInfo);
        for (ReturnPaidVo record : listGuidanceVOPageInfo.getRecords()) {
            record.setTotalDebtAmount(record.getCardDebtAmount().add(record.getDrugDebtAmount()));
            record.setReturnAmount(record.getCardDebtAmount().add(record.getDrugDebtAmount()).subtract(record.getReturnedAmount()));
        }
        return ApiResult.success(listGuidanceVOPageInfo);
    }

    @Override
    public ApiResult<?> returnPaid(ReturnPaidReqDto paidReqDto, String userName) {
        ReturnPaid returnPaid = this.getById(paidReqDto.getId());
        if (returnPaid.getCardDebtAmount().add(returnPaid.getDrugDebtAmount()).compareTo(returnPaid.getReturnedAmount().add(paidReqDto.getReturnAmount())) < 0) {
            return ApiResult.error("金额有误，超过应还款金额");
        }
        if (returnPaid.getCardDebtAmount().add(returnPaid.getDrugDebtAmount()).compareTo(returnPaid.getReturnedAmount().add(paidReqDto.getReturnAmount())) == 0) {
            returnPaid.setStatus(ReturnPaidEnum.DONE.getCode());
        }
        returnPaid.setReturnedAmount(returnPaid.getReturnedAmount().add(paidReqDto.getReturnAmount()));
        returnPaid.setUpdatedBy(userName);
        returnPaid.setUpdatedTime(LocalDateTime.now());
        this.updateById(returnPaid);
        return ApiResult.success();
    }
}




